package cn.stylefeng.guns.modular.demo.controller;


import cn.hutool.core.lang.func.Func;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISupplierService;
import cn.stylefeng.guns.dao.entity.*;
import cn.stylefeng.guns.dao.service.IStoreService;
import cn.stylefeng.guns.dao.service.IUserExtendService;
import cn.stylefeng.guns.dao.service.IUserRelationService;
import cn.stylefeng.guns.modular.demo.controller.domain.QueryUserRequest;
import cn.stylefeng.guns.modular.demo.controller.domain.UserRelationRequest;
import cn.stylefeng.guns.modular.demo.controller.domain.UserRelationVO;
import cn.stylefeng.guns.modular.demo.enums.AuthDataEnums;
import cn.stylefeng.roses.kernel.rule.enums.ResBizTypeEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author quspacedraon
 * @since 2024-02-21
 */
@RestController
@ApiResource(name = "用户扩展信息", resBizType = ResBizTypeEnum.BUSINESS, path = "/user/relation")
@Slf4j
public class UserRelationController {
    @Resource
    private IUserRelationService userRelationService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private ISupplierService supplierService;
    @Resource
    private IUserExtendService userExtendService;
    @Resource
    private IStoreService storeService;

    @PostResource(name = "供应商关联信息", path = "/detail", requiredLogin = true, requiredPermission = true)
    @ApiOperation("用户扩展信息")
    public ResponseData<List<UserRelationVO>> detail(@RequestBody QueryUserRequest queryUserRequest) {
        List<Long> userIdList = queryUserRequest.getUserIdList();
        if (CollectionUtils.isEmpty(userIdList)) {
            return new SuccessResponseData<>(Lists.newArrayList());
        }
        List<UserRelation> userRelations = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().in(UserRelation::getUserId, userIdList));
        if (CollectionUtils.isEmpty(userRelations)) {
            return new SuccessResponseData<>(Lists.newArrayList());
        }
        Map<String, List<UserRelation>> userRelationMap = userRelations.stream().collect(Collectors.groupingBy(UserRelation::getTargetType));
        List<UserRelation> goodRelations = userRelationMap.get(AuthDataEnums.goods.getType());
        List<UserRelation> supplierRelations = userRelationMap.get(AuthDataEnums.supplier.getType());
        List<UserRelation> storeRelations = userRelationMap.get(AuthDataEnums.store.getType());
        Map<String, Goods> goodsMap = Maps.newHashMap();
        Map<String, Supplier> supplierMap = Maps.newHashMap();
        Map<String, Store> storeMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(goodRelations)) {
            List<String> goodsIdList = goodRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
            goodsMap = goodsService.listByIds(goodsIdList).stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));
        }
        if (CollectionUtils.isNotEmpty(supplierRelations)) {
            List<String> supplierIdList = supplierRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
            supplierMap = supplierService.listByIds(supplierIdList).stream().collect(Collectors.toMap(Supplier::getSupplierId, Function.identity()));
        }
        if (CollectionUtils.isNotEmpty(storeRelations)) {
            List<String> supplierIdList = storeRelations.stream().map(UserRelation::getTargetId).collect(Collectors.toList());
            storeMap = storeService.list(Wrappers.<Store>lambdaQuery().in(Store::getStoreCode, supplierIdList)).stream().collect(Collectors.toMap(Store::getStoreCode, Function.identity()));
        }

        Map<Long, UserExtend> userExtendMap = userExtendService.list(Wrappers.<UserExtend>lambdaQuery().in(UserExtend::getUserId, userIdList)).stream().collect(Collectors.toMap(UserExtend::getUserId, Function.identity()));
        Map<String, Goods> finalGoodsMap = goodsMap;
        Map<String, Supplier> finalSupplierMap = supplierMap;
        Map<Long, List<UserRelation>> userIdMap = userRelations.stream().collect(Collectors.groupingBy(UserRelation::getUserId));
        Map<String, Store> finalStoreMap = storeMap;
        List<UserRelationVO> collect = userIdList.stream().map(r -> {
            UserRelationVO userRelationVO = new UserRelationVO();
            userRelationVO.setUserId(r);
            Optional.ofNullable(userExtendMap.get(r)).ifPresent(userExtend -> {
                userRelationVO.setClientId(userExtend.getClientId());
                userRelationVO.setSecret(userExtend.getSecret());
            });
            List<UserRelation> userRelationsSingle = userIdMap.get(r);
            if (CollectionUtils.isNotEmpty(userRelationsSingle)) {
                Map<String, List<UserRelation>> userRelationMapSingle = userRelationsSingle.stream().collect(Collectors.groupingBy(UserRelation::getTargetType));
                List<UserRelation> goodRelationsSingle = userRelationMapSingle.get("goods");
                List<UserRelation> supplierRelationsSingle = userRelationMapSingle.get("supplier");
                List<UserRelation> storeRelationsSingle = userRelationMapSingle.get(AuthDataEnums.store.getType());
                if (CollectionUtils.isNotEmpty(goodRelationsSingle)) {
                    userRelationVO.setGoodsList(goodRelationsSingle.stream().map(UserRelation::getTargetId).map(z -> finalGoodsMap.getOrDefault(z, null)).filter(Objects::nonNull).collect(Collectors.toList()));
                }
                if (CollectionUtils.isNotEmpty(supplierRelationsSingle)) {
                    userRelationVO.setSupplierList(supplierRelationsSingle.stream().map(UserRelation::getTargetId).map(z -> finalSupplierMap.getOrDefault(z, null)).filter(Objects::nonNull).collect(Collectors.toList()));
                }
                if (CollectionUtils.isNotEmpty(storeRelationsSingle)) {
                    userRelationVO.setStoreList(storeRelationsSingle.stream().map(UserRelation::getTargetId).map(z -> finalStoreMap.getOrDefault(z, null)).filter(Objects::nonNull).collect(Collectors.toList()));
                }
            }
            return userRelationVO;
        }).collect(Collectors.toList());


        return new SuccessResponseData<>(collect);
    }

    @PostResource(name = "供应商关联信息保存", path = "/save", requiredLogin = true, requiredPermission = true)
    @ApiOperation("供应商关联关系保存")
    public ResponseData<Boolean> save(@RequestBody UserRelationRequest userRelationRequest) {
        Long userId = userRelationRequest.getUserId();
        List<UserRelation> userExtends = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().eq(UserRelation::getUserId, userId).in(UserRelation::getTargetType, "goods", "supplier"));
        if (CollectionUtils.isNotEmpty(userExtends)) {
            List<String> collect = userExtends.stream().map(UserRelation::getUserExtend).collect(Collectors.toList());
            userRelationService.removeBatchByIds(collect);
        }

        List<UserRelation> userRelations = Lists.newArrayList();

        List<String> goodsIdList = userRelationRequest.getGoodsIdList();
        List<String> supplierIdList = userRelationRequest.getSupplierIdList();
        if (CollectionUtils.isNotEmpty(goodsIdList)) {
            userRelations.addAll(goodsIdList.stream().map(r -> {
                UserRelation userRelation = new UserRelation();
                userRelation.setUserId(userId);
                userRelation.setTargetType(AuthDataEnums.goods.getType());
                userRelation.setTargetId(r);
                return userRelation;
            }).collect(Collectors.toList()));
        }

        if (CollectionUtils.isNotEmpty(supplierIdList)) {
            userRelations.addAll(supplierIdList.stream().map(r -> {
                UserRelation userRelation = new UserRelation();
                userRelation.setUserId(userId);
                userRelation.setTargetType(AuthDataEnums.supplier.getType());
                userRelation.setTargetId(r);
                return userRelation;
            }).collect(Collectors.toList()));
        }
        userRelationService.saveBatch(userRelations);
        return new SuccessResponseData<>(true);
    }


    @PostResource(name = "门店关联信息保存", path = "/store/save", requiredLogin = true, requiredPermission = true)
    @ApiOperation("门店关联信息保存")
    public ResponseData<Boolean> saveStore(@RequestBody UserRelationRequest userRelationRequest) {
        Long userId = userRelationRequest.getUserId();
        List<UserRelation> userExtends = userRelationService.list(Wrappers.<UserRelation>lambdaQuery().eq(UserRelation::getUserId, userId)
                .in(UserRelation::getTargetType, AuthDataEnums.store.getType()));
        if (CollectionUtils.isNotEmpty(userExtends)) {
            List<String> collect = userExtends.stream().map(UserRelation::getUserExtend).collect(Collectors.toList());
            userRelationService.removeBatchByIds(collect);
        }

        List<UserRelation> userRelations = Lists.newArrayList();

        List<String> storeCodeList = userRelationRequest.getStoreCodeList();
        if (CollectionUtils.isNotEmpty(storeCodeList)) {
            userRelations.addAll(storeCodeList.stream().map(r -> {
                UserRelation userRelation = new UserRelation();
                userRelation.setUserId(userId);
                userRelation.setTargetType(AuthDataEnums.store.getType());
                userRelation.setTargetId(r);
                return userRelation;
            }).collect(Collectors.toList()));
        }
        userRelationService.saveBatch(userRelations);
        return new SuccessResponseData<>(true);
    }


}